<template>
  <div>
    <div class="recruitment-home" v-if="visible">
      <!-- 头部导航 -->
      <div class="header">
        <h1>芯芯人才推荐</h1>
        <div>
          <el-form :inline="true">
            <el-form-item>
              <el-input
                v-model="searchKeyword"
                placeholder="搜索职位/公司"
                suffix-icon="el-icon-search"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="getDataList()">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- 新增容器包裹登录和注册按钮 -->
        <div class="login-register-buttons">
          <!-- 根据是否登录显示不同按钮 -->
          <el-button v-if="!isLoggedIn" type="primary" @click="showLoginDialog = true">登录</el-button>
          <el-button v-if="!isLoggedIn" type="primary" @click="showRegisterDialog = true">注册</el-button>
          <el-button v-if="isLoggedIn" type="primary" @click="goToAdminPage">进入后台</el-button>
        </div>
      </div>
      <!-- 主内容区域，使用 flex 布局 -->
      <div class="main-content">
        <!-- 左边岗位分类区域 -->
        <div class="job-category">
          <h3>岗位分类</h3>
          <div class="category-buttons">
            <el-button v-for="category in jobCategories" :key="category" @click="filterByCategory(category)">
              {{ category }}
            </el-button>
          </div>
        </div>

        <!-- 右边职位列表区域 -->
        <div class="job-list-wrapper">
          <!-- 推荐、最新和全部选择 -->
          <div class="sort-buttons">
            <!-- <el-button :class="{ 'active': sortType === 'all' }" @click="changeSortType('all')">全部</el-button> -->
            <el-button :class="{ 'active': sortType === 'recommended' }" @click="changeSortType('recommended')">推荐</el-button>
            <el-button :class="{ 'active': sortType === 'latest' }" @click="changeSortType('latest')">最新</el-button>
          </div>
          <div class="job-list">
            <el-card v-for="job in this.jobs" :key="job.id" class="job-card" >
              <template>
                <div class="job-title" @click="goToJobDetail(job.id)" style="cursor: pointer;">
                  <span>{{ job.title + '/'}}</span>
                  <span class="job-salary">{{ job.wage }}</span>
                </div>
              </template>
              <div class="job-company">
                <span>{{ job.name+'/' }}</span>
                <span class="job-location">{{ job.area }}</span>
              </div>
              <div class="job-description">{{ job.scale }}</div>
            </el-card>
          </div>
          <!-- 分页组件 -->
          <div class="pagination-wrapper">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[12, 24, 60, 120]"
              :page-size="pageSize"
              :total="totalPage"
              layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>
          </div>
        </div>

      </div>
      <!-- 登录模态框 -->
      <el-dialog
        :visible.sync="showLoginDialog"
        title="管理员登录"
        custom-class="login-dialog"
      >
        <template #content>
          <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" status-icon>
            <el-form-item prop="userName">
              <el-input v-model="dataForm.userName" placeholder="帐号"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="dataForm.password" type="password" placeholder="密码" ></el-input>
            </el-form-item>
            <el-form-item prop="captcha">
              <el-row :gutter="20">
                <el-col :span="14">
                  <el-input v-model="dataForm.captcha" placeholder="验证码"></el-input>
                </el-col>
                <el-col :span="10" class="login-captcha">
                  <img :src="captchaPath" @click="getCaptcha()" alt="">
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
        </template>
        <template #footer>
          <el-button @click="showLoginDialog = false">取消</el-button>
          <el-button  @click="dataFormSubmit()">登录</el-button>
        </template>
      </el-dialog>
      <!-- 注册 -->
      <el-dialog
        :visible.sync="showRegisterDialog"
        title="用户注册"
        custom-class="login-dialog"
      >
        <template #content>
          <el-form :model="dataForm2" :rules="dataRule2" ref="dataForm2" @keyup.enter.native="dataForm2Submit()" status-icon>
            <el-form-item prop="userName">
              <el-input v-model="dataForm2.userName" placeholder="帐号"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="dataForm2.password" type="password" placeholder="密码"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="dataForm2.email" type="email" placeholder="邮箱"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="dataForm2.mobile" type="mobile" placeholder="电话"></el-input>
            </el-form-item>
          </el-form>
        </template>
        <template #footer>
          <el-button @click="showRegisterDialog = false">取消</el-button>
          <el-button  @click="dataForm2Submit()">注册</el-button>
        </template>
      </el-dialog>
    </div>
    <!-- 详情 -->
    <company-details v-if="companyDetailsVisible" ref="companyDetails" @goBack="goback()"></company-details>
  </div>
</template>

<script>
import { getUUID } from '@/utils'
import companyDetails from './company-details'
export default {
  data () {
    return {
      visible: true,  // 主页
      companyDetailsVisible: false,   // 职位详情
      searchKeyword: '',
      showLoginDialog: false,    // 登录弹出
      showRegisterDialog: false, // 注册弹出
      dataForm: {
        userName: '',
        password: '',
        uuid: '',
        captcha: ''
      },
      dataForm2: {
        userName: '',
        password: '',
        email: '',
        status: 1, // 状态默认为正常
        mobile: ''
      },
      dataRule: {
        userName: [
          { required: true, message: '帐号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ]
      },
      dataRule2: {
        userName: [
          { required: true, message: '帐号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '电话不能为空', trigger: 'blur' }
        ]

      },
      captchaPath: '',
      jobs: [],
      jobCategories: ['全部', '互联网', '教育', '销售'],
      selectedCategory: '全部',
      currentPage: 1,
      pageSize: 12,
      totalPage: 0,
      sortType: 'all', // 默认显示全部
      isLoggedIn: false // 新增变量，用于判断用户是否登录
    }
  },
  components: {
    companyDetails
  },
  computed: {
  },
  // 生产验证码
  created () {
    this.getCaptcha()
    this.getDataList()
    // 检查 cookie 中是否存在 token，判断用户是否登录
    this.isLoggedIn = this.$cookie.get('token') !== null
  },
  methods: {
    // 选择最新过滤
    changeSortType (type) {
      this.sortType = type
      this.currentPage = 1
      this.getChangeSortList(type)
    },
    getChangeSortList (type) {
      this.dataListLoading = true
      const params = {
        'page': this.currentPage,
        'limit': this.pageSize,
        'key': type,
        'userId': this.$store.state.user.id
      }
      console.log('请求参数:', params)
      this.$http({
        url: this.$http.adornUrl('/company/qycompany/getchangesortlist'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then(({ data }) => {
        console.log('返回数据:', data)
        if (data && data.code === 0) {
          this.jobs = data.page.list
          this.totalPage = data.page.totalCount
          console.log('职位信息为', this.jobs)
        } else {
          this.jobs = []
          this.totalPage = 0
          console.error('获取职位列表失败，错误信息:', data ? data.msg : '无响应信息')
        }
        this.dataListLoading = false
      }).catch(error => {
        console.error('请求职位列表时发生错误:', error)
        this.jobs = []
        this.totalPage = 0
        this.dataListLoading = false
      })
    },
    // 通过分类过滤
    filterByCategory (category) {
      this.sortType = 'all' // 重置 sortType 为默认值
      this.selectedCategory = category
      this.currentPage = 1
      this.selectByCategorty(category)
    },
    selectByCategorty (category) {
      this.dataListLoading = true
      const params = {
        'page': this.currentPage,
        'limit': this.pageSize,
        'key': category
      }
      console.log('请求参数:', params)
      this.$http({
        url: this.$http.adornUrl('/company/qycompany/selectbycategorty'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then(({ data }) => {
        console.log('返回数据:', data)
        if (data && data.code === 0) {
          this.jobs = data.page.list
          this.totalPage = data.page.totalCount
          console.log('职位信息为', this.jobs)
        } else {
          this.jobs = []
          this.totalPage = 0
          console.error('获取职位列表失败，错误信息:', data ? data.msg : '无响应信息')
        }
        this.dataListLoading = false
      }).catch(error => {
        console.error('请求职位列表时发生错误:', error)
        this.jobs = []
        this.totalPage = 0
        this.dataListLoading = false
      })
    },
    // 拿到所有职位信息
    getDataList () {
      this.dataListLoading = true
      const params = {
        'page': this.currentPage,
        'limit': this.pageSize,
        'key': this.searchKeyword
      }
      console.log('请求参数:', params)
      this.$http({
        url: this.$http.adornUrl('/company/qycompany/list'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then(({ data }) => {
        console.log('返回数据:', data)
        if (data && data.code === 0) {
          this.jobs = data.page.list
          this.totalPage = data.page.totalCount
          console.log('职位信息为', this.jobs)
        } else {
          this.jobs = []
          this.totalPage = 0
          console.error('获取职位列表失败，错误信息:', data ? data.msg : '无响应信息')
        }
        this.dataListLoading = false
      }).catch(error => {
        console.error('请求职位列表时发生错误:', error)
        this.jobs = []
        this.totalPage = 0
        this.dataListLoading = false
      })
    },
    // 详情组件跳转回父组件
    goback () {
      this.companyDetailsVisible = false
      this.visible = true
    },
    // 详情
    goToJobDetail (id) {
      this.visible = false
      this.companyDetailsVisible = true
      this.$nextTick(() => {
        this.$refs.companyDetails.init(id)
      })
    },
    // 注册
    dataForm2Submit () {
      this.$refs['dataForm2'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/sys/user/register'),
            method: 'post',
            data: this.$http.adornData({
              'username': this.dataForm2.userName,
              'password': this.dataForm2.password,
              'email': this.dataForm2.email,
              'mobile': this.dataForm2.mobile,
              'status': 1
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message.success('注册成功，请使用新账号登录！')
              // 关闭注册对话框
              this.showRegisterDialog = false
            }
          })
        }
      })
    },
    // 登录
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/sys/login'),
            method: 'post',
            data: this.$http.adornData({
              'username': this.dataForm.userName,
              'password': this.dataForm.password,
              'uuid': this.dataForm.uuid,
              'captcha': this.dataForm.captcha
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$cookie.set('token', data.token)
              this.showLoginDialog = false
              this.$router.replace({ name: 'home' })
              this.isLoggedIn = true // 更新登录状态
            } else {
              this.getCaptcha()
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    getCaptcha () {
      this.dataForm.uuid = getUUID()
      this.captchaPath = this.$http.adornUrl(`/captcha.jpg?uuid=${this.dataForm.uuid}`)
    },
    handleSizeChange (newSize) {
      this.pageSize = newSize
      this.currentPage = 1
      this.getDataList()
    },
    handleCurrentChange (newPage) {
      this.currentPage = newPage
      this.getDataList()
    },
    goToAdminPage () {
      // 跳转到后台页面，需要根据实际路由配置修改
      this.$router.push({ name: 'home' })
    }
  }
}
</script>

<style lang="scss">
.recruitment-home {
  width: 100%;
  height: 100vh;
  background-color: #f6f6f6;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px;
    background-color: #07141e;
    color: #fff;

    h1 {
      margin: 0;
    }

    .el-input {
      width: 300px;
    }
  }

  .main-content {
    display: flex;
    height: calc(100vh - 70px);

    .job-category {
      flex: 0.5;
      padding: 20px;
      background-color: transparent;
      box-shadow: none;

      h3 {
        margin-top: 0;
        color: #333;
      }

      .category-buttons {
        display: flex;
        flex-direction: column;
        gap: 10px;
      }

      .el-button {
        border: none;
        background-color: transparent;
        text-align: left;
        padding: 0;
        color: #666;
        transition: color 0.3s;

        &:hover {
          color: #00b38a;
        }
      }
    }

    .job-list-wrapper {
      flex: 4;
      display: flex;
      flex-direction: column;
      //justify-content: space-between;
      padding: 20px;
    }

    .sort-buttons {
      display: flex;
      gap: 10px;
      margin-bottom: 5px; // 进一步调小按钮和职业列表之间的间距
    }

    .sort-buttons .el-button {
      border: 1px solid #ccc;
      border-radius: 4px;
      padding: 6px 12px;
      color: #666;
      transition: all 0.3s;

      &.active {
        background-color: #00b38a;
        color: #fff;
        border-color: #00b38a;
      }

      &:hover {
        background-color: #00b38a;
        color: #fff;
        border-color: #00b38a;
      }
    }

    .job-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 20px;
    }

    .pagination-wrapper {
      margin-top: 20px;
      text-align: center;
    }

    .job-card {
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    .job-title {
      display: flex;
      //justify-content: space-between;
      align-items: center;
    }

    .job-salary {
      color: #00b38a;
      font-weight: bold;
    }

    .job-company {
      display: flex;
      //justify-content: space-between;
      margin-top: 10px;
      color: #666;
    }

    .job-description {
      margin-top: 10px;
      color: #999;
    }

    .login-dialog {
      .el-dialog {
        border-radius: 10px;
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
      }

      .el-dialog__header {
        background-color: #00b38a;
        color: #fff;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
      }

      .el-dialog__body {
        padding: 30px;
      }

      .el-dialog__footer {
        text-align: center;
        padding: 20px;
      }

      .el-form-item {
        margin-bottom: 20px;
      }

      .el-input {
        border: 1px solid #ccc;
        border-radius: 5px;
        padding: 10px;
        transition: border-color 0.3s;

        &:focus {
          border-color: #00b38a;
        }

        &::placeholder {
          color: #999;
        }
      }

      .el-button {
        padding: 10px 20px;
        border-radius: 5px;
        font-size: 16px;
        transition: background-color 0.3s, color 0.3s;

        &.el-button--primary {
          background-color: #00b38a;
          border-color: #00b38a;

          &:hover {
            background-color: #009a76;
            border-color: #009a76;
          }
        }

        &.el-button--default {
          background-color: #fff;
          border-color: #ccc;
          color: #666;

          &:hover {
            background-color: #f0f0f0;
            border-color: #ccc;
          }
        }
      }
    }

    .login-captcha {
      overflow: hidden;
      > img {
        width: 100%;
        cursor: pointer;
      }
    }
    // 新增按钮容器样式
    .login-register-buttons {
      display: flex;
      gap: 5px; // 调整按钮之间的间距，数值越小越紧凑
    }
  }
}
</style>
